package com.xiaoyun.service.impl;

import com.xiaoyun.bo.UserBO;
import com.xiaoyun.enums.Sex;
import com.xiaoyun.pojo.Users;
import com.xiaoyun.repository.UserRepository;
import com.xiaoyun.service.UserService;
import com.xiaoyun.utils.DateUtil;
import com.xiaoyun.utils.MD5Utils;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    public static final String USER_FACE = "";

    private final UserRepository userRepository;
    private final Sid sid;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {
        Optional<Users> users = userRepository.findByUsername(username);
        return users.isPresent();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users createUser(UserBO userBO) {
        Users users = new Users();
        String sid = this.sid.nextShort();
        users.setId(sid);
        users.setUsername(userBO.getUsername());
        try {
            users.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        users.setNickname(userBO.getUsername());
        users.setFace(USER_FACE);
        users.setBirthday(DateUtil.stringToDate("1900-01-01"));
        users.setSex(Sex.secret.type);
        users.setCreatedTime(new Date());
        users.setUpdatedTime(new Date());
        userRepository.save(users);

        return users;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Optional<Users> queryUserForLogin(String username, String md5Password) {
        return userRepository.findByUsernameAndPassword(username, md5Password);
    }

}
